package com.zhouyu.fileSync.FSserver.registerServer;

import com.zhouyu.fileSync.FScommon.api.JSONDecoder;
import com.zhouyu.fileSync.FScommon.api.JSONEncoder;
import com.zhouyu.fileSync.FScommon.commonUtils.ServerMapUtils;
import com.zhouyu.fileSync.FScommon.entities.FSClient;
import com.zhouyu.fileSync.FSserver.ServerAppContext;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by zhouyu@lightinthebox.com on 2019/8/14
 **/
public class RegisterServer implements Runnable {
    Logger logger = LogManager.getLogger(RegisterServer.class);
    /**
     * 保存所有有效的客户端节点
     */
    public static ConcurrentHashMap<String, FSClient> FSC_MAP = new ConcurrentHashMap<String, FSClient>();
    private static final EventLoopGroup bossGroup = new NioEventLoopGroup();
    private static final EventLoopGroup workerGroup = new NioEventLoopGroup();


    public void run() {
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        //创建NIOSocketChannel成功后，在进行初始化时，将它的ChannelHandler设置到ChannelPipeline中，用于处理网络IO事件
                        protected void initChannel(SocketChannel channel) throws Exception {
                            ChannelPipeline pipeline = channel.pipeline();
                            pipeline.addLast(new IdleStateHandler(0, 0, 60));
                            pipeline.addLast(new DelimiterBasedFrameDecoder(65535, Unpooled.copiedBuffer("#_@_#".getBytes())));
                            pipeline.addLast(new JSONEncoder());
                            pipeline.addLast(new JSONDecoder());
                            pipeline.addLast(new RegisterServerHandler(ServerMapUtils.getServiceMap("com.zhouyu.fileSync.FSserver")));
                        }
                    });
            int port = ServerAppContext.CONFIGS.SERVER.getPort();
            ChannelFuture cf = bootstrap.bind(port).sync();
            logger.info("netty rpc server start up! bind port:" + port);
            //等待服务端监听端口关闭
            cf.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
